package com.pzl.vca;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity {

    EditText etIP, etPushPort;
    TextView tvLocalIP;
    RadioGroup radioGroup;

    boolean remoteSurfaceInitDelay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        //对方设备的IP
        etIP = findViewById(R.id.et_videochata_ip);
        //本地设备摄像数据推流服务端口
        etPushPort = findViewById(R.id.et_videochata_push_port);
        tvLocalIP = findViewById(R.id.tv_videochat_a_localIP);
        tvLocalIP.append(getLocalIpAddress(this));
        radioGroup = findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioButton1:
                        remoteSurfaceInitDelay = true;
                        break;
                    case R.id.radioButton2:
                        remoteSurfaceInitDelay = false;
                        break;
                }

            }
        });
    }


    public void click(View view) {
        String ip = etIP.getText().toString().trim();
        String pushPort = etPushPort.getText().toString().trim();
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("ip", ip);
        intent.putExtra("pushPort", pushPort);
        intent.putExtra("remoteSurfaceInitDelay", remoteSurfaceInitDelay);
        startActivity(intent);
    }


    /**
     * 获取当前ip地址
     *
     * @param context
     * @return
     */
    private static String getLocalIpAddress(Context context) {
        try {

            WifiManager wifiManager = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } catch (Exception ex) {
            return " 获取IP出错鸟!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage();
        }
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    private static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }


}